package net.liuyimin.service;

import net.liuyimin.entity.StockEntity;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class StockService {  // StockService 默认是单例的

    // 确保是同一个资源
    private StockEntity stockEntity = new StockEntity();

    /**
     * 演示超卖现象
     */
    public void deduct() {
        stockEntity.setStockNum(stockEntity.getStockNum() - 1);
        System.out.println("库存余量：" + stockEntity.getStockNum());
    }

    /**
     * 解决超卖现象方式一：使用 synchronized 关键字
     */
    public synchronized void deductBySynchronized() {
        stockEntity.setStockNum(stockEntity.getStockNum() - 1);
        System.out.println("库存余量：" + stockEntity.getStockNum());
    }

    /**
     * 解决超卖现象方式二：使用 ReentrantLock 可重入锁
     */
    private ReentrantLock reentrantLock = new ReentrantLock();
    public void deductByReentrantLock() {
        reentrantLock.lock();
        try {
            stockEntity.setStockNum(stockEntity.getStockNum() - 1);
            System.out.println("库存余量：" + stockEntity.getStockNum());
        } finally {
            reentrantLock.unlock();
        }
    }

}
